<template>
  <div class="json-formatter">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>JSON格式化工具</h3>
          <div class="header-actions">
            <el-button-group>
              <el-button type="primary" @click="formatJson">格式化</el-button>
              <el-button type="success" @click="compressJson">压缩</el-button>
              <el-button @click="copyResult">复制结果</el-button>
              <el-button @click="clearAll">清空</el-button>
            </el-button-group>
          </div>
        </div>
      </template>
      
      <el-form>
        <el-form-item>
          <el-input
            v-model="inputJson"
            type="textarea"
            :rows="10"
            placeholder="请输入要格式化的JSON字符串"
          />
        </el-form-item>

        <el-divider>格式化结果</el-divider>

        <el-form-item>
          <div class="result-wrapper" :class="{ 'has-error': error }">
            <pre v-if="!error" class="result">{{ formattedJson }}</pre>
            <el-alert
              v-else
              type="error"
              :title="error"
              show-icon
            />
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const inputJson = ref('')
const formattedJson = ref('')
const error = ref('')

const formatJson = () => {
  if (!inputJson.value.trim()) {
    error.value = '请输入JSON字符串'
    return
  }

  try {
    const parsed = JSON.parse(inputJson.value)
    formattedJson.value = JSON.stringify(parsed, null, 2)
    error.value = ''
  } catch (e) {
    error.value = '无效的JSON格式: ' + e.message
  }
}

const compressJson = () => {
  if (!inputJson.value.trim()) {
    error.value = '请输入JSON字符串'
    return
  }

  try {
    const parsed = JSON.parse(inputJson.value)
    formattedJson.value = JSON.stringify(parsed)
    error.value = ''
  } catch (e) {
    error.value = '无效的JSON格式: ' + e.message
  }
}

const copyResult = () => {
  if (!formattedJson.value) {
    ElMessage.warning('没有可复制的内容')
    return
  }

  navigator.clipboard.writeText(formattedJson.value)
    .then(() => ElMessage.success('复制成功'))
    .catch(() => ElMessage.error('复制失败'))
}

const clearAll = () => {
  inputJson.value = ''
  formattedJson.value = ''
  error.value = ''
}
</script>

<style scoped>
.json-formatter {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

h3 {
  margin: 0;
}

.result-wrapper {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
}

.result-wrapper.has-error {
  background-color: transparent;
  padding: 0;
}

.result {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: monospace;
}
</style> 